class Seiso::ImportMaster
  # Imports a service instance document into Seiso.
  #
  # Author:: Willie Wheeler (mailto:wwheeler@expedia.com)
  # Author:: Chris Brown
  # Copyright:: Copyright (c) 2014-2016 Expedia, Inc.
  # License:: Apache 2.0
  class Importers::ServiceInstanceImporter < Importers::BaseImporter

    def initialize(api, rest_util, resolver)
      self.api = api
      self.rest_util = rest_util
      self.mapper = Mappers::ServiceInstanceMapper.new resolver
      self.repo_resource = api.serviceInstances.get

      @ipr_importer = Importers::IpAddressRoleImporter.new(api, rest_util)
      @sip_importer = Importers::ServiceInstancePortImporter.new(api, rest_util)
      @search_resource = repo_resource.search.get
    end

    def import(doc)
      import_items(doc['items'], {})
    end

    # Can't make these protected, because that prevents BaseImporter from seeing them.
#    protected

    # BaseImporter callback
    def to_search_params(doc_si, context)
      { 'key' => doc_si['key'] }
    end

    # BaseImporter callback
    def find_resource(search_params)
      @search_resource.findByKey(key: search_params['key']).get
    end

    # BaseImporter callback
    def context_for(parent_resource, parent_context)
      { 'serviceInstance' => parent_resource }
    end

    # BaseImporter callback
    def import_children_of(doc_si, context)

      # Create a default IP address role if one doesn't exist. Its name is "default".
      doc_iprs = doc_si['ipAddressRoles']
      if doc_iprs.nil? || doc_iprs.empty?
        doc_iprs = [ { 'name' => 'default', 'description' => 'Default role' } ]
      end

      # This doesn't have to be defined. For example, agents won't have ports.
      # If it's not defined, we don't need to create an empty list over it.
      doc_sips = doc_si['ports']

      @ipr_importer.import_items(doc_iprs, context)
      @sip_importer.import_items(doc_sips, context) unless doc_sips.nil?
    end
  end
end
